package com.hl.glidedemo.appWidget

import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import android.widget.RemoteViews
import com.hl.glidedemo.R
import java.io.IOException

private const val TAG = "GifWidget"

/**
 * Implementation of App Widget functionality.
 */
class GifWidget : AppWidgetProvider() {
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        // There may be multiple widgets active, so update all of them
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    override fun onEnabled(context: Context) {
        // Enter relevant functionality for when the first widget is created
    }

    override fun onDisabled(context: Context) {
        // Enter relevant functionality for when the last widget is disabled
    }
}

internal fun updateAppWidget(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetId: Int
) {
    val views = RemoteViews(context.packageName, R.layout.movie_widget)
    val subViews = RemoteViews(context.packageName, R.layout.movie_widget_item)
    views.removeAllViews(R.id.gifFlipper)

    try {
        val gifDrawable =
            pl.droidsonroids.gif.GifDrawable(context.resources, R.drawable.giphy)
        val frameCount: Int = gifDrawable.getNumberOfFrames()
        Log.e(TAG, "Number of frames: $frameCount")
        for (i in 0 until 5) {
            // 获取当前帧的 Bitmap
            val frameBitmap: Bitmap = gifDrawable.seekToFrameAndGet(i)
            Log.e(TAG, "$i frameBitmap: $frameBitmap")
            // 在此处对获取到的 Bitmap 进行操作，例如保存到文件、显示在 ImageView 等
            subViews.setImageViewBitmap(R.id.imageView, frameBitmap)
            views.addView(R.id.gifFlipper, subViews)
        }
        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views)
    } catch (e: IOException) {
        throw RuntimeException(e)
    }

}